package com.zxyankh.lijun.service;

import com.zxyankh.lijun.constants.Constant;
import com.zxyankh.lijun.dto.DisplayDto;
import com.zxyankh.lijun.dto.TimeDto;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Collections;

/**
 * @author ankh
 * @since 14.11.2018
 */
@Service
public class DisplayServiceImpl implements DisplayService {

    @Override
    public TimeDto getTime() {
        TimeDto timeDto = new TimeDto();
        LocalDateTime now = LocalDateTime.now();
        timeDto.setTotalLoveDay(ChronoUnit.DAYS.between(Constant.LOVE_TIME, now));
        timeDto.setTotalLoveHour(ChronoUnit.HOURS.between(Constant.LOVE_TIME, now)
                - 24 * timeDto.getTotalLoveDay());
        timeDto.setTotalLoveMinute(ChronoUnit.MINUTES.between(Constant.LOVE_TIME, now)
                - 60 * ChronoUnit.HOURS.between(Constant.LOVE_TIME, now));
        timeDto.setTotalLoveSecond(ChronoUnit.SECONDS.between(Constant.LOVE_TIME, now)
                - 60 * ChronoUnit.MINUTES.between(Constant.LOVE_TIME, now));
        timeDto.setTotalMeetDay(ChronoUnit.DAYS.between(Constant.MEET_TIME, now));
        timeDto.setTotalMeetHour(ChronoUnit.HOURS.between(Constant.MEET_TIME, now)
                - 24 * timeDto.getTotalMeetDay());
        timeDto.setTotalMeetMinute(ChronoUnit.MINUTES.between(Constant.MEET_TIME, now)
                - 60 * ChronoUnit.HOURS.between(Constant.MEET_TIME, now));
        timeDto.setTotalMeetSecond(ChronoUnit.SECONDS.between(Constant.MEET_TIME, now)
                - 60 * ChronoUnit.MINUTES.between(Constant.MEET_TIME, now));
        return timeDto;
    }

    @Override
    public DisplayDto getDisplayInfo() {
        DisplayDto displayDto = new DisplayDto();
        displayDto.setMeetTime(Constant.DATE_TIME_FORMATTER.format(Constant.MEET_TIME));
        displayDto.setLoveTime(Constant.DATE_TIME_FORMATTER.format(Constant.LOVE_TIME));
        try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("memory")) {
            displayDto.setMoments(Arrays.asList(StringUtils
                    .splitByWholeSeparator(IOUtils.toString(inputStream, Charset.forName("UTF-8")), System.lineSeparator())));
        } catch (Exception e) {
            displayDto.setMoments(Collections.emptyList());
        }
        return displayDto;
    }
}
